package com.toulezu.test.schedule;

import com.ckjava.xutils.Constants;
import com.toulezu.test.properties.JdbcProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
public class CustomSchedule implements Constants {

    private static Logger logger = LoggerFactory.getLogger(CustomSchedule.class);

    public static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);

    @Autowired
    private JdbcProperties jdbcProperties;

    /**
     * 系统启动的时候自动启动
     */
    /*static {
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            try {
                // 业务逻辑
                System.out.println(String.format("CustomSchedule work at:%s", DateUtils.formatTime(new Date().getTime(), Constants.TIMEFORMAT.DATETIME)));
            } catch (Throwable e) {
                logger.error("scheduleAtFixedRate has error", e);
            }

        }, 10, 10, TimeUnit.SECONDS);
    }*/

    @PostConstruct
    public void init() {
        logger.info(this.getClass() + "begin init");
        try {

            scheduledExecutorService.scheduleAtFixedRate(() -> {
                try {
                    // 业务逻辑
                    System.out.println(jdbcProperties.toString());
                } catch (Throwable e) {
                    logger.error("scheduleAtFixedRate has error", e);
                }

            }, 10, 10, TimeUnit.SECONDS);

        } catch (Exception e) {
            logger.error(this.getClass().getName().concat(".init has error"), e);
        }
        logger.info(this.getClass() + "end init");
    }
}
